package cn.wht.batch;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import cn.wht.deal.DealTask;
import cn.wht.deal.MyDealTask;
import cn.wht.enginee.ParseEnginee;
import cn.wht.enginee.ParseEngineeFactory;

/**
 * @Author: haoting.wang
 * @Date: Created in 上午10:46 2017/6/16
 */
public class BatchTask {

    private static int QUEUE_SIZE       = 500;
    private static int TASK_THREAD_SIZE = Runtime.getRuntime().availableProcessors() * 2;

    private DealTask   dealTask;

    public BatchTask(DealTask dealTask){
        this.dealTask = dealTask;
    }

    public void doBatch(File file) {

        if (!file.exists()) {
            return;
        }
        BlockingQueue<Map> queue = new ArrayBlockingQueue<Map>(QUEUE_SIZE);

        readFile(queue, file);

        dealFile(queue);
    }

    /**
     * 读取解析文件
     * 
     * @param queue
     * @param file
     */
    public void readFile(BlockingQueue<Map> queue, File file) {

        // 读取 文件
        ParseEnginee parseEnginee = ParseEngineeFactory.getInstance(queue, file);
        new Thread(parseEnginee).start();

    }

    /**
     * 处理解析后的文件
     * 
     * @param queue
     */
    public void dealFile(BlockingQueue<Map> queue) {

        // 设置处理内容
        dealTask.setQueue(queue);

        // 开启多线程处理
        for (int i = 0; i < TASK_THREAD_SIZE; i++) {
            new Thread(dealTask, "dealThread" + i).start();
        }
    }

    public static void main(String[] args) {

        File file = new File("/Users/haoting.wang/IdeaProjects/batchImport/src/test.txt");
        MyDealTask myDealTask = new MyDealTask();
        BatchTask batchTask = new BatchTask(myDealTask);
        batchTask.doBatch(file);
    }
}
